import json

from channels.generic.websocket import AsyncWebsocketConsumer


class MessageConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        await self.channel_layer.group_add(
            'message',
            self.channel_name
        )
        await self.accept()

    async def receive(self, text_data=None):
        jo = json.loads(text_data)
        typ = jo.get('type')
        data = jo.get('data')
        if typ == 'auth':
            goods_sn = data
            resp = {
                'type': typ,
                'data': {
                    'symbol': goods_sn,
                }
            }
            await self.send(text_data=json.dumps(resp))

    async def pay_notice(self, event):
        data = event['data']
        text_data = ''
        if type(data) == dict:
            text_data = json.dumps({
                'type': 'pay_notice',
                'data': data.get('msg', '')
            })
        await self.send(text_data=text_data)
